package com.cus.tom.transfer.utils;

import android.util.Log;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

/**
 * Created by lei on 2017/8/21.
 */

public class ComUtility {
    private static final String TAG = "ComUtility";

    private static String readStream(BufferedReader in) {
        try {
            StringBuffer stringBuffer = new StringBuffer();
            String line = null;
            while ((line = in.readLine()) != null) {
                stringBuffer.append(line + "\n");
            }
            return stringBuffer.toString();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String[] rootCommand(String command) {
        Log.e("tagg", "do " + command);
        String[] r = doRootCommand(command);
        if (r == null) {
            r = command(command);
        }
        return r;
    }

    /**
     * 执行控制台命令，参数为命令行字符串方式，申请Root控制权限
     */
    private static String[] doRootCommand(String command) {
        Process process = null;
        OutputStream out = null;
        InputStream in = null, err = null;
        DataOutputStream os = null;
        InputStreamReader isIn = null, isErr = null;
        BufferedReader bIn = null, bErr = null;

        try {
            process = Runtime.getRuntime().exec("su");//执行这一句，superuser.apk就会弹出授权对话框
            out = process.getOutputStream();
            os = new DataOutputStream(out);
            os.writeBytes(command + "\n");
            os.writeBytes("exit\n");
            os.flush();

            in = process.getInputStream();
            err = process.getErrorStream();

            isIn = new InputStreamReader(in);
            isErr = new InputStreamReader(err);

            bIn = new BufferedReader(isIn);
            bErr = new BufferedReader(isErr);

            String s0 = readStream(bIn);
            String s1 = readStream(bErr);

            process.waitFor();
            Log.d(TAG, "获取root权限成功");
            Log.d(TAG, s0 + "\n" + s1);
            return new String[]{s0, s1};

        } catch (Exception e) {
            Log.e(TAG, "获取root权限失败： " + e.getMessage());
            return null;
        } finally {
            close(bIn);
            close(bErr);
            close(isIn);
            close(isErr);
            close(in);
            close(err);
            close(out);
            close(os);
            if (process != null) {
                process.destroy();
            }
        }
    }

    private static String[] command(String command) {
        Process process = null;
        OutputStream out = null;
        InputStream in = null, err = null;
        InputStreamReader isIn = null, isErr = null;
        BufferedReader bIn = null, bErr = null;

        try {
            process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", command});
//            process = Runtime.getRuntime().exec(command);//执行这一句，superuser.apk就会弹出授权对话框
            out = process.getOutputStream();

            in = process.getInputStream();
            err = process.getErrorStream();

            isIn = new InputStreamReader(in);
            isErr = new InputStreamReader(err);

            bIn = new BufferedReader(isIn);
            bErr = new BufferedReader(isErr);

            String s0 = readStream(bIn);
            String s1 = readStream(bErr);

            process.waitFor();
            Log.d(TAG, "无root权限");
            Log.d(TAG, s0 + "\n" + s1);
            return new String[]{s0, s1};

        } catch (Exception e) {
            Log.e(TAG, "获取root权限失败： " + e.getMessage());
            return null;
        } finally {
            close(bIn);
            close(bErr);
            close(isIn);
            close(isErr);
            close(in);
            close(err);
            close(out);
            if (process != null) {
                process.destroy();
            }
        }
    }

    public static void execCommand(String command) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        Process proc = runtime.exec(command);
        //proc = Runtime.getRuntime().exec("su");
        try {
            if (proc.waitFor() != 0) {
                System.err.println("exit value = " + proc.exitValue());
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    proc.getInputStream()));
            StringBuffer stringBuffer = new StringBuffer();
            String line = null;
            while ((line = in.readLine()) != null) {
                stringBuffer.append(line + "-");
            }
            //打印出执行cmd命令后返回的数据
            Log.w(TAG, stringBuffer.toString());

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行命令
     *
     * @param command
     * @return
     */
    public static String android_command(String command) {
        Process process = null;
        BufferedReader reader = null;
        StringBuffer buffer = new StringBuffer();
        String temp;
        try {
            process = Runtime.getRuntime().exec(command);
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((temp = reader.readLine()) != null) {
                buffer.append(temp);
            }
            return buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }

    static void close(Closeable c) {
        if (c != null) {
            try {
                c.close();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }
}
